// src/store/cart.js
import { defineStore } from 'pinia'
import { getCartList, addToCart, updateCartItem, deleteCartItem, batchDeleteCartItems } from '@/api/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', {
    state: () => ({
        cartItems: [],
        cartCount: 0,
        loading: false
    }),

    getters: {
        // 购物车总价
        totalPrice: (state) => {
            return state.cartItems.reduce((total, item) => {
                return total + (item.price * item.quantity)
            }, 0)
        },

        // 选中商品总价
        selectedTotalPrice: (state) => {
            return state.cartItems
                .filter(item => item.selected)
                .reduce((total, item) => {
                    return total + (item.price * item.quantity)
                }, 0)
        },

        // 选中商品数量
        selectedCount: (state) => {
            return state.cartItems.filter(item => item.selected).length
        }
    },

    actions: {
        // 获取购物车列表
        async fetchCartList() {
            this.loading = true
            try {
                const userId = localStorage.getItem('userId')
                if (!userId) {
                    this.cartItems = []
                    this.cartCount = 0
                    return
                }

                const response = await getCartList({ userId, pageSize: 100 })
                if (response.data.code === 1) {
                    this.cartItems = response.data.data.records.map(item => ({
                        ...item,
                        selected: false // 添加选中状态
                    }))
                    this.cartCount = this.cartItems.length
                }
            } catch (error) {
                console.error('获取购物车列表失败:', error)
                ElMessage.error('获取购物车列表失败')
            } finally {
                this.loading = false
            }
        },

        // 添加商品到购物车
        async addItemToCart(productData) {
            try {
                const userId = localStorage.getItem('userId')
                if (!userId) {
                    ElMessage.warning('请先登录')
                    return false
                }

                // 检查商品是否已在购物车中
                const existingItem = this.cartItems.find(item =>
                    item.productId === productData.productId
                )

                if (existingItem) {
                    // 如果商品已存在，增加数量
                    await this.updateItemQuantity(existingItem.cartId, existingItem.quantity + 1)
                } else {
                    // 添加新商品
                    const cartData = {
                        userId: parseInt(userId),
                        productId: productData.productId,
                        quantity: productData.quantity || 1,
                        createTime: new Date().toISOString()
                    }

                    const response = await addToCart(cartData)
                    if (response.data.code === 1) {
                        ElMessage.success('添加到购物车成功')
                        await this.fetchCartList() // 刷新购物车列表
                        return true
                    }
                }
            } catch (error) {
                console.error('添加购物车失败:', error)
                ElMessage.error('添加购物车失败')
                return false
            }
        },

        // 更新商品数量
        async updateItemQuantity(cartId, quantity) {
            try {
                const item = this.cartItems.find(item => item.cartId === cartId)
                if (!item) return

                const updateData = {
                    cartId,
                    userId: item.userId,
                    productId: item.productId,
                    quantity,
                    createTime: item.createTime
                }

                const response = await updateCartItem(updateData)
                if (response.data.code === 1) {
                    // 更新本地状态
                    const index = this.cartItems.findIndex(item => item.cartId === cartId)
                    if (index !== -1) {
                        this.cartItems[index].quantity = quantity
                    }
                    ElMessage.success('更新成功')
                }
            } catch (error) {
                console.error('更新购物车失败:', error)
                ElMessage.error('更新失败')
            }
        },

        // 删除购物车商品
        async removeItem(cartId) {
            try {
                const response = await deleteCartItem(cartId)
                if (response.data.code === 1) {
                    this.cartItems = this.cartItems.filter(item => item.cartId !== cartId)
                    this.cartCount = this.cartItems.length
                    ElMessage.success('删除成功')
                }
            } catch (error) {
                console.error('删除购物车商品失败:', error)
                ElMessage.error('删除失败')
            }
        },

        // 批量删除选中商品
        async removeSelectedItems() {
            try {
                const selectedItems = this.cartItems.filter(item => item.selected)
                if (selectedItems.length === 0) {
                    ElMessage.warning('请选择要删除的商品')
                    return
                }

                const cartIds = selectedItems.map(item => item.cartId)
                const response = await batchDeleteCartItems(cartIds)

                if (response.data.code === 1) {
                    this.cartItems = this.cartItems.filter(item => !item.selected)
                    this.cartCount = this.cartItems.length
                    ElMessage.success('删除成功')
                }
            } catch (error) {
                console.error('批量删除失败:', error)
                ElMessage.error('删除失败')
            }
        },

        // 切换商品选中状态
        toggleItemSelection(cartId) {
            const item = this.cartItems.find(item => item.cartId === cartId)
            if (item) {
                item.selected = !item.selected
            }
        },

        // 全选/取消全选
        toggleAllSelection(selected) {
            this.cartItems.forEach(item => {
                item.selected = selected
            })
        }
    }
})
